<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="订单号">
              <a-input v-model="queryParam.orderNo" placeholder="请输入订单号" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="客户项目">
              <a-input v-model="queryParam.customerProjectName" placeholder="请输入客户项目名称" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="库存状态">
              <a-select v-model="queryParam.stockStatus" placeholder="请选择库存状态" allowClear>
                <a-select-option :value="1">正常</a-select-option>
                <a-select-option :value="2">预留</a-select-option>
                <a-select-option :value="3">冻结</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="refreshTable" icon="reload">刷新</a-button>
      <a-button type="primary" icon="bar-chart" @click="showStatistics">库存统计</a-button>
    </div>

    <!-- 订单库存汇总表格 -->
    <a-table
      ref="table"
      size="middle"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :expandedRowKeys="expandedRowKeys"
      @expand="onExpand">

      <template slot="action" slot-scope="text, record">
        <a @click="viewOrderDetail(record)">查看详情</a>
        <a-divider type="vertical" />
        <a @click="adjustOrderInventory(record)">批量调整</a>
        <a-divider type="vertical" />
        <a @click="reserveOrderInventory(record)">批量预留</a>
      </template>

      <template slot="expandedRowRender" slot-scope="record">
        <a-table
          :columns="detailColumns"
          :dataSource="record.inventoryDetails"
          :pagination="false"
          size="small">
          
          <template slot="stockStatus" slot-scope="text">
            <a-tag v-if="text == 1" color="green">正常</a-tag>
            <a-tag v-else-if="text == 2" color="orange">预留</a-tag>
            <a-tag v-else-if="text == 3" color="red">冻结</a-tag>
          </template>

          <template slot="detailAction" slot-scope="text, detailRecord">
            <a @click="viewInventoryDetail(detailRecord)">详情</a>
            <a-divider type="vertical" />
            <a @click="adjustInventory(detailRecord)">调整</a>
            <a-divider type="vertical" />
            <a @click="reserveInventory(detailRecord)" v-if="detailRecord.availableQuantity > 0">预留</a>
            <a @click="releaseInventory(detailRecord)" v-if="detailRecord.reservedQuantity > 0">释放</a>
          </template>
        </a-table>
      </template>
    </a-table>

    <!-- 模态框组件 -->
    <inventory-detail-modal ref="inventoryDetailModal" @ok="refreshTable" />
    <inventory-adjust-modal ref="inventoryAdjustModal" @ok="refreshTable" />
    <inventory-reserve-modal ref="inventoryReserveModal" @ok="refreshTable" />
    <inventory-release-modal ref="inventoryReleaseModal" @ok="refreshTable" />
    <inventory-statistics-modal ref="inventoryStatisticsModal" />
  </a-card>
</template>

<script>
import { getAction } from '@/api/manage'
import InventoryDetailModal from './modules/InventoryDetailModal'
import InventoryAdjustModal from './modules/InventoryAdjustModal'
import InventoryReserveModal from './modules/InventoryReserveModal'
import InventoryReleaseModal from './modules/InventoryReleaseModal'
import InventoryStatisticsModal from './modules/InventoryStatisticsModal'

export default {
  name: 'InventoryByOrder',
  components: {
    InventoryDetailModal,
    InventoryAdjustModal,
    InventoryReserveModal,
    InventoryReleaseModal,
    InventoryStatisticsModal
  },
  data() {
    return {
      queryParam: {},
      dataSource: [],
      expandedRowKeys: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条记录`,
      },
      columns: [
        {
          title: '订单号',
          dataIndex: 'orderNo',
          width: 150,
          fixed: 'left'
        },
        {
          title: '客户项目',
          dataIndex: 'customerProjectName',
          width: 200,
          ellipsis: true
        },
        {
          title: '门窗总数',
          dataIndex: 'totalWindowCount',
          width: 100,
          align: 'center'
        },
        {
          title: '库存总数量',
          dataIndex: 'totalQuantity',
          width: 120,
          align: 'center'
        },
        {
          title: '可用数量',
          dataIndex: 'availableQuantity',
          width: 100,
          align: 'center',
          customRender: (text) => <span style="color: #52c41a">{text}</span>
        },
        {
          title: '预留数量',
          dataIndex: 'reservedQuantity',
          width: 100,
          align: 'center',
          customRender: (text) => <span style="color: #faad14">{text}</span>
        },
        {
          title: '库存金额',
          dataIndex: 'totalAmount',
          width: 120,
          align: 'right',
          customRender: (text) => text ? `¥${text.toFixed(2)}` : '¥0.00'
        },
        {
          title: '入库时间',
          dataIndex: 'inboundTime',
          width: 150,
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      detailColumns: [
        {
          title: '门窗系列',
          dataIndex: 'windowSeries',
          width: 120
        },
        {
          title: '门窗类型',
          dataIndex: 'windowType',
          width: 120
        },
        {
          title: '规格',
          dataIndex: 'specifications',
          width: 150
        },
        {
          title: '仓库',
          dataIndex: 'warehouseName',
          width: 100
        },
        {
          title: '库位',
          dataIndex: 'locationName',
          width: 100
        },
        {
          title: '批次号',
          dataIndex: 'batchNo',
          width: 120
        },
        {
          title: '总数量',
          dataIndex: 'totalQuantity',
          width: 80,
          align: 'center'
        },
        {
          title: '可用',
          dataIndex: 'availableQuantity',
          width: 60,
          align: 'center'
        },
        {
          title: '预留',
          dataIndex: 'reservedQuantity',
          width: 60,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'stockStatus',
          width: 80,
          scopedSlots: { customRender: 'stockStatus' }
        },
        {
          title: '操作',
          dataIndex: 'detailAction',
          width: 150,
          scopedSlots: { customRender: 'detailAction' }
        }
      ]
    }
  },
  created() {
    this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const params = {
          ...this.queryParam,
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        };

        const res = await getAction('/wms/finished-goods/inventory/by-order', params);
        if (res.success) {
          this.dataSource = res.result.records || [];
          this.pagination.total = res.result.total || 0;
        }
      } catch (error) {
        this.$message.error('加载数据失败');
        console.error('加载数据失败', error);
      } finally {
        this.loading = false;
      }
    },
    searchQuery() {
      this.pagination.current = 1;
      this.loadData();
    },
    searchReset() {
      this.queryParam = {};
      this.pagination.current = 1;
      this.loadData();
    },
    refreshTable() {
      this.loadData();
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadData();
    },
    async onExpand(expanded, record) {
      if (expanded && !record.inventoryDetails) {
        // 加载订单库存详情
        try {
          const res = await getAction(`/wms/finished-goods/inventory/order-details/${record.orderNo}`);
          if (res.success) {
            this.$set(record, 'inventoryDetails', res.result || []);
          }
        } catch (error) {
          this.$message.error('加载库存详情失败');
        }
      }
    },
    viewOrderDetail(record) {
      this.$message.info('订单详情功能开发中...');
    },
    adjustOrderInventory(record) {
      this.$message.info('批量调整功能开发中...');
    },
    reserveOrderInventory(record) {
      this.$message.info('批量预留功能开发中...');
    },
    viewInventoryDetail(record) {
      this.$refs.inventoryDetailModal.show(record);
    },
    adjustInventory(record) {
      this.$refs.inventoryAdjustModal.show(record);
    },
    reserveInventory(record) {
      this.$refs.inventoryReserveModal.show(record);
    },
    releaseInventory(record) {
      this.$refs.inventoryReleaseModal.show(record);
    },
    showStatistics() {
      this.$refs.inventoryStatisticsModal.show();
    }
  }
}
</script>

<style scoped>
.table-page-search-wrapper {
  margin-bottom: 16px;
}
.table-operator {
  margin-bottom: 16px;
}
</style>
